package leetcode.day_2020_2021_1_18_2021_1_24;

/**
 * https://leetcode-cn.com/problems/longest-palindromic-substring/
 * 5. 最长回文子串
 */
public class Leetcode0005 {
    public static void main(String[] args) {
        System.out.println(longestPalindrome("babad"));
        System.out.println(longestPalindrome("cbbbd"));
        System.out.println(longestPalindrome("a"));
        System.out.println(longestPalindrome("ac"));
        System.out.println(longestPalindrome("aefbb"));
    }


    public static String longestPalindrome(String s) {
        String res = "";
        for(int i=0; i<s.length(); i++) {
            String res1 = palindrome(s, i, i);
            String res2 = palindrome(s, i, i+1);
            res = res1.length() > res.length() ? res1 : res;
            res = res2.length() > res.length() ? res2 : res;
        }
        return res;
    }

    public static String palindrome(String s, int l, int r) {
        while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
            l--; r++;
        }
        if (l+1 >= r) {     // 为了防止越界
            return "";
        } else if (l == -1) {       // l为-1的时候
            return s.substring(l+1, r-l-1);
        } else {        // 其他情况
            return s.substring(l+1, r);
        }
    }
}
